from flask import Flask, request, render_template, jsonify, send_file
import os
import sys
import tempfile
import soundfile as sf
import numpy as np
import datetime
import time

# 确保可以导入本地模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 如果从包内导入失败，则尝试直接导入
try:
    from .config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, SECRET_KEY, DEBUG
    from .models import db, TTSTransformation
    from .tts_processor import TTSProcessor
except ImportError:
    from config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, SECRET_KEY, DEBUG
    from models import db, TTSTransformation
    from tts_processor import TTSProcessor

# 创建Flask应用实例
app = Flask(__name__)

# 直接设置必要的配置项
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS
app.config['SECRET_KEY'] = SECRET_KEY
app.config['DEBUG'] = DEBUG

# 初始化数据库
with app.app_context():
    db.init_app(app)
    db.create_all()

# 初始化TTS处理器
processor = TTSProcessor()

@app.route('/')
def index():
    """首页，提供Web界面"""
    return render_template('index.html', voices=processor.get_available_voices(), languages=processor.get_available_languages())

@app.route('/api/tts', methods=['POST'])
def tts_api():
    """提供文字转声音的API接口"""
    try:
        # 获取请求参数
        data = request.json
        text = data.get('text', '')
        voice = data.get('voice', 'expr-voice-5-m')
        speed = data.get('speed', 1.0)
        language = data.get('language', 'en-us')
        
        if not text:
            return jsonify({'error': 'Text parameter is required'}), 400
        
        # 检查速度参数
        try:
            speed = float(speed)
        except ValueError:
            return jsonify({'error': 'Speed must be a number'}), 400
        
        # 检查语音参数
        if voice not in processor.get_available_voices():
            return jsonify({
                'error': f'Voice "{voice}" not available',
                'available_voices': processor.get_available_voices()
            }), 400
        
        # 检查语言参数
        if language not in processor.get_available_languages():
            return jsonify({
                'error': f'Language "{language}" not available',
                'available_languages': processor.get_available_languages()
            }), 400
        
        # 生成音频
        start_time = time.time()
        audio = processor.generate_audio(text, voice, speed, language)
        process_time = time.time() - start_time
        
        # 创建临时文件保存音频
        with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
            sf.write(temp_file.name, audio, 24000)
            temp_filename = temp_file.name
        
        # 保存记录到数据库
        record = TTSTransformation(
            text=text,
            voice=voice,
            speed=speed,
            duration=process_time,
            timestamp=datetime.datetime.now()
        )
        db.session.add(record)
        db.session.commit()
        
        # 提供音频文件下载
        response = send_file(temp_filename, mimetype='audio/wav')
        
        # 清理临时文件的回调
        @response.call_on_close
        def cleanup():
            try:
                os.remove(temp_filename)
            except:
                pass
        
        return response
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/history')
def get_history():
    """获取转换历史记录"""
    try:
        # 获取参数
        limit = request.args.get('limit', 100, type=int)
        offset = request.args.get('offset', 0, type=int)
        
        # 查询数据库
        records = TTSTransformation.query.order_by(TTSTransformation.timestamp.desc()).offset(offset).limit(limit).all()
        
        # 转换为JSON格式
        result = []
        for record in records:
            result.append({
                'id': record.id,
                'text': record.text,
                'voice': record.voice,
                'speed': record.speed,
                'duration': record.duration,
                'timestamp': record.timestamp.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)